package org.example.iris.service.impl;

import org.example.iris.mapper.UserMapper;
import org.example.iris.entity.User;
import org.example.iris.service.UserService;
import org.example.iris.utils.AliyunSmsUtil;
import org.example.iris.utils.EmailCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private EmailCodeUtil emailCodeUtil;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendPhoneCode(String phoneNum) throws Exception {
        String phoneCode = AliyunSmsUtil.sendPhoneCode(phoneNum);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(phoneNum, phoneCode, 5, TimeUnit.MINUTES);
    }

    @Override
    public void sendEmailCode(String email) throws Exception {
        String emailCode = emailCodeUtil.sendCode(email);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(email, emailCode, 5, TimeUnit.MINUTES);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User findByEmail(String email) {
        return userMapper.findByEmail(email);
    }

    @Override
    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    @Override
    public User findById(Integer userId) {
        return userMapper.findById(userId);
    }

    @Override
    public void updatePhone(String phoneNum, Integer userId) {
        userMapper.updatePhone(phoneNum, userId);
    }

    @Override
    public void updateEmail(String email, Integer userId) {
        userMapper.updateEmail(email, userId);
    }

    @Override
    public void updatePassword(User user) {
        userMapper.updatePassword(user);
    }
}
